//
//  AIGirlMessageSettingView.swift
//  AIGirl
//
//  Created by Rae on 2023/12/29.
//

import UIKit
import SwiftEntryKit

class AIGirlMessageSettingView: UIView, AnimationProtocol, AnimationDelegate,UorInXNetworkProtocol {

    func animationContainerViewSize() -> CGSize {
        CGSize(width: .screenWidth, height: 630.0)
    }
    
    func animationContainerViewStyle() -> AnimationViewStyle {
        .bottom
    }
    
//    func animationContainerScreenInteraction() -> EKAttributes.UserInteraction {
//        .init()
//    }
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(22.5).mode(.scaleAspectFill).end()
    private var nameLabel = UIIconButton(style: .trailing(itemSpace: 4.5))
    private lazy var ageLabel = c_make_ex(UILabel.self)
        .color(.white).font(16.font_medium).alignment(.center)
        .text("Age:18").end()
    private lazy var avatarButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(17.font_bold).corner(20)
        .text("Change avatar").end()
    private let interestLab = c_make_ex(UILabel.self)
        .color(.white).text("your interest tags.")
        .font(16.font_bold).end()
    private lazy var interestButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(16.font_bold).corner(15)
        .text("Change").end()
    private let selfieLab = c_make_ex(UILabel.self)
        .color(.white).text("Selfie")
        .font(16.font_bold).end()
    private let interestView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let selfieView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var editGirlInfoClosure: (() -> Void)?
    var changeAvatarClosure: (() -> Void)?
    var changeInterestClosure: ((_ dataSource: [AIGirlInterestModel]) -> Void)?
    var changeGirlPhotoDtosClosure: (() -> Void)?
    var photoDtos = [AIGirlDiscoverDetailPicModel](){
        didSet{
            selfieView.reloadData()
        }
    }
    
    func updateGirlInfo(){
        var nameStr = "AI_Girl"
        var ageStr = "18"
        var avatarString = ""
        if let name = UserDefaultsManager.getString(forKey: .grilName) {
            nameStr = name
        }
        if let age = UserDefaultsManager.getString(forKey: .grilAge) {
            ageStr = age
        }
        if let avatar = UserDefaultsManager.getString(forKey: .girlAvatar) {
            avatarString = avatar
        }
        ageLabel.text = "Age:" + ageStr
        nameLabel.setTitle(nameStr, for: .normal)
        iconImageView.loadImage(url: avatarString)
        selfieView.reloadData()
    }
    
    var interestData: [AIGirlUserInterestItemModel]? {
        didSet{
            if let array = interestData, array.count > 0 {
                interestView.reloadData()
            }
        }
    }
    
    var allInterestData: [AIGirlInterestModel]? {
        didSet{
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                guard let array = self.interestData, array.count > 0 else { return }
                guard var allArr = self.allInterestData, allArr.count > 0 else { return }
                for obj in array {
                    if let index = allArr.firstIndex(where: { $0.id == obj.id }) {
                        // 如果找到相同 id 的对象，进行更新操作
                        allArr[index].isSel = true
                    }
                }
                self.changeInData = allArr
            }
        }
    }
    var changeInData: [AIGirlInterestModel]?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        layer.cornerRadius = 30
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        backgroundColor = "#262C61".toColor
        subviews{
            iconImageView
            nameLabel
            ageLabel
            avatarButton
            interestLab
            interestButton
            interestView
            selfieLab
            selfieView
        }
        
        iconImageView.top(45).size(90).centerHorizontally()
        nameLabel.width(.screenWidth - 100.0).centerHorizontally()
        nameLabel.Top == iconImageView.Bottom + 14
        ageLabel.centerHorizontally()
        ageLabel.Top == nameLabel.Bottom + 8
        avatarButton.width(200).height(40).centerHorizontally()
        avatarButton.Top == ageLabel.Bottom + 20
        interestLab.leading(15)
        interestLab.Top == avatarButton.Bottom + 30
        interestButton.trailing(15).height(30).width(100)
        interestButton.CenterY == interestLab.CenterY
        interestView.leading(0).trailing(0).height(40)
        interestView.Top == interestButton.Bottom + 15
        selfieLab.leading(15)
        selfieLab.Top == interestView.Bottom + 25
        selfieView.leading(0).trailing(0).height(155)
        selfieView.Top == selfieLab.Bottom + 15
        
        nameLabel.style { v in
            v.setImage("AIGirl_Profile_edit".toImage, for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.titleLabel?.font = 16.font_italic
            v.iconSize = CGSize(width: 21, height: 21)
            v.setTitle("Dseoints", for: .normal)
            v.contentHorizontalAlignment = .center
        }
        let interestLayout = UICollectionViewFlowLayout()
        interestLayout.minimumLineSpacing = 10
        interestLayout.minimumInteritemSpacing = 10
        interestLayout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        interestLayout.scrollDirection = .horizontal
        interestView.style { v in
            v.collectionViewLayout = interestLayout
            v.backgroundColor = .clear
            v.register(AIGirlInterestItem.self, forCellWithReuseIdentifier: AIGirlInterestItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        let selfieLayout = UICollectionViewFlowLayout()
        selfieLayout.minimumLineSpacing = 10
        selfieLayout.minimumInteritemSpacing = 10
        selfieLayout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        selfieLayout.scrollDirection = .horizontal
        selfieLayout.itemSize = CGSize(width: 115, height: 155)
        selfieView.style { v in
            v.collectionViewLayout = selfieLayout
            v.backgroundColor = .clear
            v.register(AIGirlProfileGetItem.self, forCellWithReuseIdentifier: AIGirlProfileGetItem.description())
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        
        nameLabel.addTarget(self, action: #selector(clickGirlInfoButton), for: .touchUpInside)
        avatarButton.addTarget(self, action: #selector(clickChangeAvatarButton), for: .touchUpInside)
        interestButton.addTarget(self, action: #selector(clickChangeButton), for: .touchUpInside)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func clickGirlInfoButton(){
        
        animation.animation(dismiss: self){
            self.editGirlInfoClosure?()
        }
        
    }
    @objc private func clickChangeAvatarButton(){
        
        animation.animation(dismiss: self){
            self.changeAvatarClosure?()
        }
        
    }
    @objc private func clickChangeButton(){
        
        guard let arr = changeInData else { return }
        animation.animation(dismiss: self){
            self.changeInterestClosure?(arr)
        }
        
    }
    
}

extension AIGirlMessageSettingView: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == interestView {
            return interestData?.count ?? 0
        }
        return photoDtos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == interestView {
            guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlInterestItem.description(), for: indexPath) as? AIGirlInterestItem else { return UICollectionViewCell() }
            item.msgModel = interestData?[indexPath.row]
            return item
        }
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlProfileGetItem.description(), for: indexPath) as? AIGirlProfileGetItem else { return UICollectionViewCell() }
        item.msgModel = photoDtos[indexPath.row]
        item.updateSelState()
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        let model = dataArray[indexPath.row]
//        var w = model.title.caculateWidth(CGSize(width: 50, height: 30), 14.font_regular!)
//        w = w + 30.0
        if collectionView == interestView {
            let model = interestData?[indexPath.row]
//            var w = model?.name.caculateWidth(CGSize(width: 110, height: 40), 16.font_medium!)
//            w = (w ?? 0) + 30.0
            guard let md = model else { return .zero}
            var w = (md.name as NSString).size(withAttributes: [NSAttributedString.Key.font: 16.font_medium!]).width
            w = w + 30.0
            return CGSize(width: w , height: 40)
        }
        return CGSize(width: 115, height: 155)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if photoDtos.count > indexPath.row, collectionView == selfieView {
            let model = photoDtos[indexPath.row]
            if model.isLook {
                animation.animation(dismiss: self){
                    var photos = [AIGirlDiscoverDetailPicModel]()
                    for md in self.photoDtos {
                        if md.isLook {
                            photos.append(md)
                        }
                    }
                    let albumVC = AIGirlAlbumViewController()
                    albumVC.photoDtos = photos
                    UIApplication.topController()?.present(albumVC, animated: true)
                }
            }else{
                
                if model.vipUnlock {
                    if GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
                        unlockPhoto(id: model.id)
                    }else{
                        self.animation.animation(show: AIGirlMsgLevelDetailView())
                    }
                }else{
                    if model.lookPrice > 0 && GlobalTool.userModel?.money ?? 0 < model.lookPrice {
                        self.animation.animation(show: AIGirlMessagePremiumView())
                    }else if model.lookPrice > 0 && GlobalTool.userModel?.money ?? 0 >= model.lookPrice {
                        unlockPhoto(id: model.id)
                    }
                }
                
            }
        }
       
    }
    
    func unlockPhoto(id:Int)  {
        self.request.start(.unlockMessage(id: id, type: 0), completion: { result in
            if result.isSuccessful {
                "success!".toast_success
                GlobalTool.refreshUserInfo()

                
                self.changeGirlPhotoDtosClosure?()
              
            }
        })
    }
}
